/**
 * - 作者: DoooReyn
 * - 日期: 2023.10.29
 * - 名称: Singleton
 * - 描述: 单例模式
 */
export abstract class Singleton {
    /**
     * 获取单例
     * @param this 单例引用
     * @param args 初始化参数列表
     * @returns
     */
    public static getInstance<T extends Singleton>(this: new () => T, ...args: any[]): T {
        let instance: T;
        if (!(<any>this).instance) {
            instance = (<any>this).instance = new this();
            instance.init(...args);
        }
        return instance!;
    }

    /**
     * 初始化否
     */
    protected _inited: boolean = false;

    /**
     * 初始化
     * @param args 初始化参数列表
     */
    protected init(...args: any[]): void {
        if (!this._inited) {
            this.onInitialize(...args);
            this._inited = true;
        }
    }

    /**
     * 销毁单例
     */
    public destroy() {
        this._inited = false;
        this.onDestroy();
        delete (<any>this).instance;
    }

    /**
     * 初始化回调，供重载
     */
    protected abstract onInitialize(...args: any[]): void;

    /**
     * 销毁回调，供重载
     */
    protected abstract onDestroy(): void;
}
